package middleware

import (
	"errors"
	"goadmin/api"
	"goadmin/utils"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

func Logged() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			api.Res(c, api.CodeNoAuth, "token required")
			c.Abort()
			return
		}
		userId, err := utils.ParseToken(token)
		if err != nil {
			if errors.Is(err, jwt.ErrTokenExpired) {
				// 已过期
				api.Res(c, api.CodeTokenExpired, "token expired")
				c.Abort()
				return
			} else {
				api.Res(c, api.CodeNoAuth, "token invalid")
				c.Abort()
				return
			}
		}
		c.Set("user_id", userId)
		c.Next()
	}
}

func NotLogged() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			c.Next()
			return
		}
		_, err := utils.ParseToken(token)
		if err != nil {
			c.Next()
			return
		}
		api.Res(c, api.CodeHasLogin, "already logged in")
		c.Abort()
	}
}
